package com.systar.activity.monitor;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.concurrent.atomic.AtomicInteger;

import org.joda.time.Duration;
import org.joda.time.Instant;

public class ActivityRecorder
{
	private final String activityName;
	private Instant activityStart;
	private Instant activityEnd;
	private AtomicInteger activityCount;

	public ActivityRecorder(String activityName)
	{
		this.activityName = activityName;
		activityStart = null;
		activityEnd = null;
		activityCount = new AtomicInteger(0);
	}
	
	public void start()
	{
		activityStart = Instant.now();
		System.out.println("Start for  "+activityName);
	}
	
	public void increment()
	{
		activityCount.addAndGet(1);
	}
	
	public void end()
	{
		checkNotNull(activityStart);
		activityEnd = Instant.now();
		System.out.println("End for  "+activityName);
	}
	
	public double getRate()
	{
		checkNotNull(activityStart);
		checkNotNull(activityEnd);
		
		Duration duration = new Duration(activityStart, activityEnd);
		if (duration.isLongerThan(Duration.ZERO))
		{
			// return activity speed (number of activity per second)
			return (activityCount.get() * 1000 ) / duration.getMillis();
		}
		return 0.0;
	}
	
	public String formatResult()
	{
		double rate = getRate();
		
		String format = String.format("%s : %f /s", activityName, rate);
		return format;
	}
}
